package com.bub.pay.api.controller;

import com.bub.pay.core.entity.vo.user.LoginVo;
import com.bub.pay.core.manager.user.UserCommonManager;
import com.bub.pay.framework.common.entity.model.SessionModel;
import com.bub.pay.framework.common.util.IpRemote;
import com.bub.pay.framework.shiro.authc.UserToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import static com.bub.pay.framework.common.constant.SystemConstants.SYS_TYPE_ADMIN;



@RestController
@RequestMapping("/admin")
public class LoginController {

	@Resource
	private UserCommonManager userCommonManager;


    @PostMapping("/login")
    public Object login(HttpServletRequest httpRequest, @RequestBody @Valid LoginVo reqVo) throws Exception {
        reqVo.setUserType(SYS_TYPE_ADMIN);
        Subject subject = SecurityUtils.getSubject();
        final String reqIp = IpRemote.getIpAddr(httpRequest);
        UserToken userToken = new UserToken(SYS_TYPE_ADMIN, reqVo.getLoginName(), reqVo.getPassword(), reqVo.getGoogleCode(),reqIp);
        subject.login(userToken);
//        subject.isAuthenticated();
        SessionModel sessionModel = userCommonManager.userLogin(httpRequest, reqVo);

        return sessionModel;
    }

    @PostMapping("/loginOut")
    public void loginOut(HttpServletRequest httpRequest) throws Exception {
        userCommonManager.deleteSession(httpRequest.getHeader("UserId"), httpRequest);
    }

}
